<?php

class FieldValidator{
	public $regexp='/*/';
	public $message='invalid_format';
	public function __construct($p){
		if($p)$this->regexp=$p;	
	}
	
	public function validateValue($v){
		return preg_match($this->regexp, $v)?NULL:$this->message;
	}

}

class FieldValidatorNotNULL extends FieldValidator{
	public function __construct(){
		$this->regexp='/.+/';
	}
}

class FieldValidatorRegExp extends FieldValidator{	
	public function __construct($p){
		if(!is_string($p))throw new Exception('Regexp validator must receive the regexp string in constructor!');
		$this->regexp=$p;
	}
}

class FieldValidatorEmail extends FieldValidator{
	public function __construct(){
		$this->regexp='/^([a-zA-Z0-9._])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/';
	}
	
	public function emailvalidateValue($v){
		if(preg_match($this->regexp,$v)){
		list($username,$domain)=split('@',$email);
    if(!checkdnsrr($domain,'MX')) {
      return 'emial_provider_cannot_be_verified';
    }
    return NULL;
	}else	
		return 'address_format_not_valid';
	}
}

class FieldValidatorPhone extends FieldValidator{
	public function __construct(){
		$this->regexp='/[0-9- \/]{1,12}/';
	}
}

class FieldValidatorDate extends FieldValidator{
	public function __construct(){
		$this->regexp='#\d{4}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[01])#';
	}
}

class FieldValidatorUsername extends FieldValidator{
	public function __construct(){
		$this->regexp='#[a-zA-Z0-9_\.]+#';
	}
}

class FieldValidatorReal extends FieldValidator{
	public function __construct(){
		$this->regexp='/[0-9]{1,20}\\.{0,1}[0-9]{1,3}/';
	}
}

class FieldValidatorCaptcha extends FieldValidator{
	public function __construct(){
		$this->message='captcha_error';
		if(!isset($_SESSION['captcha']))$_SESSION['captcha']='';
	}
	
	public function validateValue($v){
		$result=(md5(strtoupper($v))==$_SESSION['captcha']);
		return $result?NULL:$this->message;
	}
};
